

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="Node 学习笔记Node.js 基础初识 NodejsNode.js 是一个基于 Chrome V8 引擎 的 JavaScript 运行时环境  基于 Express 框架，可以快速构建 Web 应用 基于 Electron 框架，可以构建跨平台的桌面应用 基于 restify 框架，可以快速构建 API 接口项目 读写和操作数据库、创建实用的命令行工具辅助前端开发、etc…  Buffer">
<meta property="og:type" content="article">
<meta property="og:title" content="node学习笔记">
<meta property="og:url" content="http://dayu.com/2022/11/23/node%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="Node 学习笔记Node.js 基础初识 NodejsNode.js 是一个基于 Chrome V8 引擎 的 JavaScript 运行时环境  基于 Express 框架，可以快速构建 Web 应用 基于 Electron 框架，可以构建跨平台的桌面应用 基于 restify 框架，可以快速构建 API 接口项目 读写和操作数据库、创建实用的命令行工具辅助前端开发、etc…  Buffer">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-23T07:49:29.000Z">
<meta property="article:modified_time" content="2023-09-13T02:50:28.096Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="node">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>node学习笔记 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_3846514_kabxni94auf.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/gundongtiao.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"dayu.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives">
                <i class="iconfont icon-books"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories">
                <i class="iconfont icon-th-large"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" href="javascript:;" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-book"></i>
                文档
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="node学习笔记"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        dayu
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-23 15:49" pubdate>
           2022 年 11 月 23 日 , 下午 03:49 , 星期三
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          20k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          167 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">node学习笔记</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Node-学习笔记"><a href="#Node-学习笔记" class="headerlink" title="Node 学习笔记"></a>Node 学习笔记</h1><h2 id="Node-js-基础"><a href="#Node-js-基础" class="headerlink" title="Node.js 基础"></a>Node.js 基础</h2><h3 id="初识-Nodejs"><a href="#初识-Nodejs" class="headerlink" title="初识 Nodejs"></a>初识 Nodejs</h3><p><strong>Node.js 是一个基于 Chrome V8 引擎 的 JavaScript 运行时环境</strong></p>
<ul>
<li>基于 Express 框架，可以快速构建 Web 应用</li>
<li>基于 Electron 框架，可以构建跨平台的桌面应用</li>
<li>基于 restify 框架，可以快速构建 API 接口项目</li>
<li>读写和操作数据库、创建实用的命令行工具辅助前端开发、etc…</li>
</ul>
<h3 id="Buffer-缓冲区"><a href="#Buffer-缓冲区" class="headerlink" title="Buffer 缓冲区"></a>Buffer 缓冲区</h3><ul>
<li>Buffer 的结构与数组类似，操作方法也与数组类似</li>
<li>数组不能存储二进制文件，Buffer 是专门存储二进制数据的</li>
<li>Buffer 存储的是二进制数据，显示时以 16 进制的形式显示</li>
<li>Buffer 每一个元素范围是 00<del>ff，即 0</del>255、00000000~11111111</li>
<li>每一个元素占用一个字节内存</li>
<li>Buffer 是对底层内存的直接操作，因此大小一旦确定就不能修改</li>
</ul>
<p>Buffer 常用方法：</p>
<ul>
<li><code>Buffer.from(str[, encoding])</code>：将一个字符串转换为 Buffer</li>
<li><code>Buffer.alloc(size)</code>：创建指定大小的 Buffer</li>
<li><code>Buffer.alloUnsafe(size)</code>：创建指定大小的 Buffer，可能包含敏感数据（分配内存时不会清除内存残留的数据）</li>
<li><code>buf.toString()</code>：将 Buffer 数据转为字符串</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> str = <span class="hljs-string">&#x27;Hello前端&#x27;</span><br><br><span class="hljs-keyword">var</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(str)<br><br><span class="hljs-comment">// 占用内存的大小，一个汉字3字节 13</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>)<br><span class="hljs-comment">// 字符串的长度 7</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(str.<span class="hljs-property">length</span>)<br><span class="hljs-comment">// 8进制输出第一个元素 145</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf[<span class="hljs-number">1</span>].<span class="hljs-title function_">toString</span>(<span class="hljs-number">8</span>))<br><br><span class="hljs-comment">//创建一个10个字节的buffer</span><br><span class="hljs-keyword">var</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>)<br><span class="hljs-comment">//通过索引，来操作buf中的元素</span><br>buf2[<span class="hljs-number">0</span>] = <span class="hljs-number">88</span><br>buf2[<span class="hljs-number">1</span>] = <span class="hljs-number">255</span><br>buf2[<span class="hljs-number">2</span>] = <span class="hljs-number">0xaa</span><br>buf2[<span class="hljs-number">3</span>] = <span class="hljs-number">255</span><br><br><span class="hljs-keyword">var</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf3)<br></code></pre></td></tr></table></figure>

<h3 id="fs-文件系统模块"><a href="#fs-文件系统模块" class="headerlink" title="fs 文件系统模块"></a>fs 文件系统模块</h3><ul>
<li>fs 模块中所有的操作都有两种形式可供选择:同步和异步</li>
<li>同步文件系统会阻塞程序的执行，也就是除非操作完毕，否则不会向下执行代码</li>
<li>异步文件系统不会阻塞程序的执行，而是在操作完成时，通过回调函数将结果返回</li>
<li>实际开发很少用同步方式，因此只介绍异步方式</li>
</ul>
<p>打开模式：</p>
<ul>
<li><code>r</code>：读取文件，文件不存在抛异常</li>
<li><code>r+</code>：读写文件，文件不存在抛异常</li>
<li><code>rs</code>：同步模式下打开文件用于读取</li>
<li><code>rs+</code>: 同步模式下打开文件用于读写</li>
<li><code>w</code>: 写文件，不存在则创建，存在则覆盖原有内容</li>
<li><code>wx</code>: 写文件，文件存在打开失败</li>
<li><code>w+</code>: 读写文件，不存在创建，存在截断</li>
<li><code>wx+</code>: 读写，存在打开失败</li>
<li><code>a</code>: 追加，不存在创建</li>
<li><code>ax</code>: 追加，存在失败</li>
<li><code>a+</code>: 追加和读取，不存在创建</li>
<li><code>ax+</code>: 追加和读取，存在失败</li>
</ul>
<h4 id="读取文件"><a href="#读取文件" class="headerlink" title="读取文件"></a>读取文件</h4><h5 id="简单文件读取"><a href="#简单文件读取" class="headerlink" title="简单文件读取"></a>简单文件读取</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">fs.<span class="hljs-title function_">readFile</span>(path[, options], callback)<br></code></pre></td></tr></table></figure>

<ul>
<li>path：文件路径</li>
<li>options：配置选项，若是字符串则指定编码格式</li>
<li>encoding：编码格式</li>
<li>flag：打开方式</li>
<li>callback：回调函数</li>
<li>err：错误信息</li>
<li>data：读取的数据，如果未指定编码格式则返回一个 Buffer</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><br>fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">&#x27;./files/1.txt&#x27;</span>, <span class="hljs-string">&#x27;utf-8&#x27;</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) =&gt; &#123;<br>  <span class="hljs-keyword">if</span>(err) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;failed!&#x27;</span> + err.<span class="hljs-property">message</span>)<br>  &#125;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;content:&#x27;</span> + data)<br>&#125;)<br><br><span class="hljs-comment">// 复制文件内容</span><br>fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">&quot;C:/Users/笔记.mp3&quot;</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) &#123;<br>	<span class="hljs-keyword">if</span>(!err) &#123;<br>		<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);<br>		<span class="hljs-comment">// 将data写入到文件中</span><br>		fs.<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">&quot;C:/Users/hello.jpg&quot;</span>, data, <span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)&#123;<br>			<span class="hljs-keyword">if</span>(!err)&#123;<br>				<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;文件写入成功&quot;</span>);<br>			&#125;<br>		&#125; );<br>	&#125;<br>&#125;);<br></code></pre></td></tr></table></figure>

<h5 id="流式文件读取"><a href="#流式文件读取" class="headerlink" title="流式文件读取"></a>流式文件读取</h5><ul>
<li>简单文件读取的方式会一次性读取文件内容到内存中，若文件较大，会占用过多内存影响系统性能，且读取速度慢</li>
<li>大文件适合用流式文件读取，它会分多次将文件读取到内存中</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><br><span class="hljs-comment">// 创建一个可读流</span><br><span class="hljs-keyword">var</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">&#x27;C:/Users/笔记.mp3&#x27;</span>)<br><span class="hljs-comment">// 创建一个可写流</span><br><span class="hljs-keyword">var</span> ws = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">&#x27;a.mp3&#x27;</span>)<br><br><span class="hljs-comment">// 监听流的开启和关闭</span><br><span class="hljs-comment">// 这几个监听不是必须的</span><br>rs.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;open&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;可读流打开了~~&#x27;</span>)<br>&#125;)<br><br>rs.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;close&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;可读流关闭了~~&#x27;</span>)<br>  <span class="hljs-comment">//数据读取完毕，关闭可写流</span><br>  ws.<span class="hljs-title function_">end</span>()<br>&#125;)<br><br>ws.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;open&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;可写流打开了~~&#x27;</span>)<br>&#125;)<br><br>ws.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;close&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;可写流关闭了~~&#x27;</span>)<br>&#125;)<br><br><span class="hljs-comment">//要读取一个可读流中的数据，要为可读流绑定一个data事件，data事件绑定完毕自动开始读取数据</span><br>rs.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;data&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data)<br>  <span class="hljs-comment">//将读取到的数据写入到可写流中</span><br>  ws.<span class="hljs-title function_">write</span>(data)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>简便方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><br><span class="hljs-keyword">var</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">&#x27;C:/Users/lilichao/Desktop/笔记.mp3&#x27;</span>)<br><span class="hljs-keyword">var</span> ws = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">&#x27;b.mp3&#x27;</span>)<br><br><span class="hljs-comment">// pipe()可以将可读流中的内容，直接输出到可写流中</span><br>rs.<span class="hljs-title function_">pipe</span>(ws)<br></code></pre></td></tr></table></figure>

<h4 id="写入文件"><a href="#写入文件" class="headerlink" title="写入文件"></a>写入文件</h4><h5 id="简单文件写入"><a href="#简单文件写入" class="headerlink" title="简单文件写入"></a>简单文件写入</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">fs.<span class="hljs-title function_">writeFile</span>(file, data[, options], callback)<br></code></pre></td></tr></table></figure>

<ul>
<li>file：文件路径</li>
<li>data：写入内容</li>
<li>options：配置选项，包含 encoding, mode, flag；若是字符串则指定编码格式</li>
<li>callback：回调函数</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br>fs.<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">&#x27;./files/2.txt&#x27;</span>, <span class="hljs-string">&#x27;Hello Nodejs&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) &#123;<br>  <span class="hljs-keyword">if</span> (err) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;failed!&#x27;</span> + err.<span class="hljs-property">message</span>)<br>  &#125;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;success!&#x27;</span>)<br>&#125;)<br><br>fs.<span class="hljs-title function_">writeFile</span>(<br>  <span class="hljs-string">&#x27;C:/Users/hello.txt&#x27;</span>,<br>  <span class="hljs-string">&#x27;通过 writeFile 写入的内容&#x27;</span>,<br>  &#123; <span class="hljs-attr">flag</span>: <span class="hljs-string">&#x27;w&#x27;</span> &#125;,<br>  <span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) &#123;<br>    <span class="hljs-keyword">if</span> (!err) &#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;写入成功！&#x27;</span>)<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err)<br>    &#125;<br>  &#125;<br>)<br></code></pre></td></tr></table></figure>

<h5 id="流式文件写入"><a href="#流式文件写入" class="headerlink" title="流式文件写入"></a>流式文件写入</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 同步、异步、简单文件的写入都不适合大文件的写入，性能较差，容易导致内存溢出</span><br><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><br><span class="hljs-comment">// 创建一个可写流</span><br><span class="hljs-keyword">var</span> ws = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">&#x27;hello3.txt&#x27;</span>)<br><br>ws.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;open&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;流打开了~~&#x27;</span>)<br>&#125;)<br><br>ws.<span class="hljs-title function_">once</span>(<span class="hljs-string">&#x27;close&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;流关闭了~~&#x27;</span>)<br>&#125;)<br><br><span class="hljs-comment">// 通过ws向文件中输出内容</span><br>ws.<span class="hljs-title function_">write</span>(<span class="hljs-string">&#x27;通过可写流写入文件的内容&#x27;</span>)<br>ws.<span class="hljs-title function_">write</span>(<span class="hljs-string">&#x27;1&#x27;</span>)<br>ws.<span class="hljs-title function_">write</span>(<span class="hljs-string">&#x27;2&#x27;</span>)<br>ws.<span class="hljs-title function_">write</span>(<span class="hljs-string">&#x27;3&#x27;</span>)<br>ws.<span class="hljs-title function_">write</span>(<span class="hljs-string">&#x27;4&#x27;</span>)<br><br><span class="hljs-comment">// 关闭流</span><br>ws.<span class="hljs-title function_">end</span>()<br></code></pre></td></tr></table></figure>

<h4 id="路径动态拼接问题-dirname"><a href="#路径动态拼接问题-dirname" class="headerlink" title="路径动态拼接问题 __dirname"></a>路径动态拼接问题 __dirname</h4><ul>
<li>在使用 fs 模块操作文件时，如果提供的操作路径是以 <code>./</code> 或 <code>../</code> 开头的相对路径时，容易出现路径动态拼接错误的问题</li>
<li>原因：代码在运行的时候，会以执行 node 命令时所处的目录，动态拼接出被操作文件的完整路径</li>
<li>解决方案：在使用 fs 模块操作文件时，直接提供完整的路径，从而防止路径动态拼接的问题</li>
<li><code>__dirname</code> 获取文件所处的绝对路径</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js">fs.<span class="hljs-title function_">readFile</span>(__dirname + <span class="hljs-string">&#x27;/files/1.txt&#x27;</span>, <span class="hljs-string">&#x27;utf8&#x27;</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="其他操作"><a href="#其他操作" class="headerlink" title="其他操作"></a>其他操作</h4><p>验证路径是否存在：</p>
<ul>
<li><code>fs.exists(path, callback)</code></li>
<li><code>fs.existsSync(path)</code></li>
</ul>
<p>获取文件信息：</p>
<ul>
<li><code>fs.stat(path, callback)</code></li>
<li><code>fs.stat(path)</code></li>
</ul>
<p>删除文件：</p>
<ul>
<li><code>fs.unlink(path, callback)</code></li>
<li><code>fs.unlinkSync(path)</code></li>
</ul>
<p>列出文件：</p>
<ul>
<li><code>fs.readdir(path[,options], callback)</code></li>
<li><code>fs.readdirSync(path[, options])</code></li>
</ul>
<p>截断文件：</p>
<ul>
<li><code>fs.truncate(path, len, callback)</code></li>
<li><code>fs.truncateSync(path, len)</code></li>
</ul>
<p>建立目录：</p>
<ul>
<li><code>fs.mkdir(path[, mode], callback)</code></li>
<li><code>fs.mkdirSync(path[, mode])</code></li>
</ul>
<p>删除目录：</p>
<ul>
<li><code>fs.rmdir(path, callback)</code></li>
<li><code>fs.rmdirSync(path)</code></li>
</ul>
<p>重命名文件和目录：</p>
<ul>
<li><code>fs.rename(oldPath, newPath, callback)</code></li>
<li><code>fs.renameSync(oldPath, newPath)</code></li>
</ul>
<p>监视文件更改：</p>
<ul>
<li><code>fs.watchFile(filename[, options], listener)</code></li>
</ul>
<h3 id="path-路径模块"><a href="#path-路径模块" class="headerlink" title="path 路径模块"></a>path 路径模块</h3><p>path 模块是 Node.js 官方提供的、用来处理路径的模块。它提供了一系列的方法和属性，用来满足用户对路径的处理需求。</p>
<h4 id="路径拼接-path-join"><a href="#路径拼接-path-join" class="headerlink" title="路径拼接 path.join()"></a>路径拼接 <code>path.join()</code></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>)<br><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;fs&#x27;</span>)<br><br><span class="hljs-comment">// 注意 ../ 会抵消前面的路径</span><br><span class="hljs-comment">// ./ 会被忽略</span><br><span class="hljs-keyword">const</span> pathStr = path.<span class="hljs-title function_">join</span>(<span class="hljs-string">&#x27;/a&#x27;</span>, <span class="hljs-string">&#x27;/b/c&#x27;</span>, <span class="hljs-string">&#x27;../../&#x27;</span>, <span class="hljs-string">&#x27;./d&#x27;</span>, <span class="hljs-string">&#x27;e&#x27;</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pathStr) <span class="hljs-comment">// \a\d\e</span><br><br>fs.<span class="hljs-title function_">readFile</span>(<br>  path.<span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">&#x27;./files/1.txt&#x27;</span>),<br>  <span class="hljs-string">&#x27;utf8&#x27;</span>,<br>  <span class="hljs-keyword">function</span> (<span class="hljs-params">err, dataStr</span>) &#123;<br>    <span class="hljs-keyword">if</span> (err) &#123;<br>      <span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err.<span class="hljs-property">message</span>)<br>    &#125;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dataStr)<br>  &#125;<br>)<br></code></pre></td></tr></table></figure>

<h4 id="获取路径中文件名-path-basename"><a href="#获取路径中文件名-path-basename" class="headerlink" title="获取路径中文件名 path.basename()"></a>获取路径中文件名 <code>path.basename()</code></h4><p>使用 <code>path.basename()</code> 方法，可以获取路径中的最后一部分，常通过该方法获取路径中的文件名</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">path.<span class="hljs-title function_">basename</span>(path[, ext])<br></code></pre></td></tr></table></figure>

<ul>
<li>path: 文件路径</li>
<li>ext: 文件扩展名</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>)<br><br><span class="hljs-comment">// 定义文件的存放路径</span><br><span class="hljs-keyword">const</span> fpath = <span class="hljs-string">&#x27;/a/b/c/index.html&#x27;</span><br><br><span class="hljs-keyword">const</span> fullName = path.<span class="hljs-title function_">basename</span>(fpath)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(fullName) <span class="hljs-comment">// index.html</span><br><br><span class="hljs-keyword">const</span> nameWithoutExt = path.<span class="hljs-title function_">basename</span>(fpath, <span class="hljs-string">&#x27;.html&#x27;</span>)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(nameWithoutExt) <span class="hljs-comment">// index</span><br></code></pre></td></tr></table></figure>

<h4 id="获取路径中文件扩展名-path-extname"><a href="#获取路径中文件扩展名-path-extname" class="headerlink" title="获取路径中文件扩展名 path.extname()"></a>获取路径中文件扩展名 <code>path.extname()</code></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>)<br><br><span class="hljs-keyword">const</span> fpath = <span class="hljs-string">&#x27;/a/b/c/index.html&#x27;</span><br><br><span class="hljs-keyword">const</span> fext = path.<span class="hljs-title function_">extname</span>(fpath)<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(fext) <span class="hljs-comment">// .html</span><br></code></pre></td></tr></table></figure>

<h3 id="http-模块"><a href="#http-模块" class="headerlink" title="http 模块"></a>http 模块</h3><p><strong>http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。</strong></p>
<h4 id="创建基本的-Web-服务器"><a href="#创建基本的-Web-服务器" class="headerlink" title="创建基本的 Web 服务器"></a>创建基本的 Web 服务器</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;http&#x27;</span>)<br><br><span class="hljs-comment">// 创建 web 服务器实例</span><br><span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>()<br><br><span class="hljs-comment">// 为服务器实例绑定 request 事件，监听客户端的请求</span><br>server.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;request&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) &#123;<br>  <span class="hljs-keyword">const</span> url = req.<span class="hljs-property">url</span><br>  <span class="hljs-keyword">const</span> method = req.<span class="hljs-property">method</span><br>  <span class="hljs-keyword">const</span> str = <span class="hljs-string">`Your request url is <span class="hljs-subst">$&#123;url&#125;</span>, and request method is <span class="hljs-subst">$&#123;method&#125;</span>`</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(str)<br><br>  <span class="hljs-comment">// 设置 Content-Type 响应头，解决中文乱码的问题</span><br>  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Content-Type&#x27;</span>, <span class="hljs-string">&#x27;text/html; charset=utf-8&#x27;</span>)<br>  <span class="hljs-comment">// 向客户端响应内容</span><br>  res.<span class="hljs-title function_">end</span>(str)<br>&#125;)<br><br>server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;server running at http://127.0.0.1:8080&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="实现简陋路由效果"><a href="#实现简陋路由效果" class="headerlink" title="实现简陋路由效果"></a>实现简陋路由效果</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;http&#x27;</span>)<br><span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>()<br><br>server.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;request&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">const</span> url = req.<span class="hljs-property">url</span><br>  <span class="hljs-comment">// 设置默认的响应内容为 404 Not found</span><br>  <span class="hljs-keyword">let</span> content = <span class="hljs-string">&#x27;&lt;h1&gt;404 Not found!&lt;/h1&gt;&#x27;</span><br>  <span class="hljs-comment">// 判断用户请求的是否为 / 或 /index.html 首页</span><br>  <span class="hljs-comment">// 判断用户请求的是否为 /about.html 关于页面</span><br>  <span class="hljs-keyword">if</span> (url === <span class="hljs-string">&#x27;/&#x27;</span> || url === <span class="hljs-string">&#x27;/index.html&#x27;</span>) &#123;<br>    content = <span class="hljs-string">&#x27;&lt;h1&gt;首页&lt;/h1&gt;&#x27;</span><br>  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (url === <span class="hljs-string">&#x27;/about.html&#x27;</span>) &#123;<br>    content = <span class="hljs-string">&#x27;&lt;h1&gt;关于页面&lt;/h1&gt;&#x27;</span><br>  &#125;<br><br>  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Content-Type&#x27;</span>, <span class="hljs-string">&#x27;text/html; charset=utf-8&#x27;</span>)<br>  res.<span class="hljs-title function_">end</span>(content)<br>&#125;)<br><br>server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;server running at http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h3 id="模块化"><a href="#模块化" class="headerlink" title="模块化"></a>模块化</h3><h4 id="模块化概念"><a href="#模块化概念" class="headerlink" title="模块化概念"></a>模块化概念</h4><ul>
<li>模块化是指解决一个复杂问题时，自顶向下逐层把系统划分为若干模块的过程，模块是可组合、分解和更换的单元。</li>
<li>模块化可提高代码的复用性和可维护性，实现按需加载。</li>
<li>模块化规范是对代码进行模块化拆分和组合时需要遵守的规则，如使用何种语法格式引用模块和向外暴露成员。</li>
</ul>
<h4 id="Node-js-中模块的分类"><a href="#Node-js-中模块的分类" class="headerlink" title="Node.js 中模块的分类"></a>Node.js 中模块的分类</h4><ul>
<li>内置模块</li>
<li>自定义模块</li>
<li>第三方模块</li>
</ul>
<h4 id="Node-js-中的模块作用域"><a href="#Node-js-中的模块作用域" class="headerlink" title="Node.js 中的模块作用域"></a>Node.js 中的模块作用域</h4><ul>
<li>和函数作用域类似，在自定义模块中定义的变量、方法等成员，只能在当前模块内被访问，这种模块级别的访问限制，叫做模块作用域</li>
<li>防止全局变量污染</li>
</ul>
<h4 id="模块作用域的成员"><a href="#模块作用域的成员" class="headerlink" title="模块作用域的成员"></a>模块作用域的成员</h4><ul>
<li>自定义模块中都有一个 <code>module</code> 对象，存储了和当前模块有关的信息</li>
<li>在自定义模块中，可以使用 <code>module.exports</code> 对象，将模块内的成员共享出去，供外界使用。导入自定义模块时，得到的就是 <code>module.exports</code> 指向的对象。</li>
<li>默认情况下，<code>exports</code> 和 <code>module.exports</code> 指向同一个对象。最终共享的结果，以 <code>module.exports</code> 指向的对象为准。</li>
</ul>
<h4 id="CommonJS-模块化规范"><a href="#CommonJS-模块化规范" class="headerlink" title="CommonJS 模块化规范"></a>CommonJS 模块化规范</h4><ul>
<li>每个模块内部，<code>module</code> 变量代表当前模块</li>
<li><code>module</code> 变量是一个对象，<code>module.exports</code> 是对外的接口</li>
<li>加载某个模块即加载该模块的 <code>module.exports</code> 属性</li>
</ul>
<h4 id="模块加载机制"><a href="#模块加载机制" class="headerlink" title="模块加载机制"></a>模块加载机制</h4><p><strong>模块第一次加载后会被缓存，即多次调用 <code>require()</code> 不会导致模块的代码被执行多次，提高模块加载效率。</strong></p>
<h5 id="内置模块加载"><a href="#内置模块加载" class="headerlink" title="内置模块加载"></a>内置模块加载</h5><p>内置模块加载优先级最高。</p>
<h5 id="自定义模块加载"><a href="#自定义模块加载" class="headerlink" title="自定义模块加载"></a>自定义模块加载</h5><p>加载自定义模块时，路径要以 <code>./</code> 或 <code>../</code> 开头，否则会作为内置模块或第三方模块加载。</p>
<p>导入自定义模块时，若省略文件扩展名，则 Node.js 会按顺序尝试加载文件：</p>
<ul>
<li>按确切的文件名加载</li>
<li>补全 <code>.js</code> 扩展名加载</li>
<li>补全 <code>.json</code> 扩展名加载</li>
<li>补全 <code>.node</code> 扩展名加载</li>
<li>报错</li>
</ul>
<h5 id="第三方模块加载"><a href="#第三方模块加载" class="headerlink" title="第三方模块加载"></a>第三方模块加载</h5><ul>
<li>若导入第三方模块， Node.js 会从<strong>当前模块的父目录</strong>开始，尝试从 <code>/node_modules</code> 文件夹中加载第三方模块。</li>
<li>如果没有找到对应的第三方模块，则移动到再<strong>上一层父目录</strong>中，进行加载，直到<strong>文件系统的根目录</strong>。</li>
</ul>
<p>例如，假设在 <code>C:\Users\bruce\project\foo.js</code> 文件里调用了 <code>require(&#39;tools&#39;)</code>，则 Node.js 会按以下顺序查找：</p>
<ul>
<li><code>C:\Users\bruce\project\node_modules\tools</code></li>
<li><code>C:\Users\bruce\node_modules\tools</code></li>
<li><code>C:\Users\node_modules\tools</code></li>
<li><code>C:\node_modules\tools</code></li>
</ul>
<h5 id="目录作为模块加载"><a href="#目录作为模块加载" class="headerlink" title="目录作为模块加载"></a>目录作为模块加载</h5><p>当把目录作为模块标识符进行加载的时候，有三种加载方式：</p>
<ul>
<li>在被加载的目录下查找 <code>package.json</code> 的文件，并寻找 <code>main</code> 属性，作为 <code>require()</code> 加载的入口</li>
<li>如果没有 <code>package.json</code> 文件，或者 <code>main</code> 入口不存在或无法解析，则 Node.js 将会试图加载目录下的 <code>index.js</code> 文件。</li>
<li>若失败则报错</li>
</ul>
<h2 id="Express"><a href="#Express" class="headerlink" title="Express"></a>Express</h2><h3 id="Express-初体验"><a href="#Express-初体验" class="headerlink" title="Express 初体验"></a>Express 初体验</h3><h4 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h4><p>安装</p>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">npm <span class="hljs-keyword">install</span> express<br></code></pre></td></tr></table></figure>

<p>创建服务器，监听客户端请求，并返回内容：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-comment">// 创建 web 服务器</span><br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><br><span class="hljs-comment">// 监听客户端的 GET 和 POST 请求，并向客户端响应具体的内容</span><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;zs&#x27;</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">20</span>, <span class="hljs-attr">gender</span>: <span class="hljs-string">&#x27;男&#x27;</span> &#125;)<br>&#125;)<br>app.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;请求成功&#x27;</span>)<br>&#125;)<br><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// 通过 req.query 可以获取到客户端发送过来的查询参数</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(req.<span class="hljs-property">query</span>)<br>  res.<span class="hljs-title function_">send</span>(req.<span class="hljs-property">query</span>)<br>&#125;)<br><br><span class="hljs-comment">// 这里的 :id 是一个动态的参数</span><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/:ids/:username&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// req.params 是动态匹配到的 URL 参数，默认是一个空对象</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(req.<span class="hljs-property">params</span>)<br>  res.<span class="hljs-title function_">send</span>(req.<span class="hljs-property">params</span>)<br>&#125;)<br><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;express server running at http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="托管静态资源"><a href="#托管静态资源" class="headerlink" title="托管静态资源"></a>托管静态资源</h4><ul>
<li>通过 <code>express.static()</code> 方法可创建静态资源服务器，向外开放访问静态资源。</li>
<li>Express 在指定的静态目录中查找文件，并对外提供资源的访问路径，存放静态文件的目录名不会出现在 URL 中</li>
<li>访问静态资源时，会根据托管顺序查找文件</li>
<li>可为静态资源访问路径添加前缀</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">use</span>(express.<span class="hljs-title function_">static</span>(<span class="hljs-string">&#x27;public&#x27;</span>))<br>app.<span class="hljs-title function_">use</span>(express.<span class="hljs-title function_">static</span>(<span class="hljs-string">&#x27;files&#x27;</span>))<br>app.<span class="hljs-title function_">use</span>(<span class="hljs-string">&#x27;/bruce&#x27;</span>, express.<span class="hljs-title function_">static</span>(<span class="hljs-string">&#x27;bruce&#x27;</span>))<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">可直接访问 public, files 目录下的静态资源</span><br><span class="hljs-comment">http://localhost:3000/images/bg.jpg</span><br><span class="hljs-comment">http://localhost:3000/css/style.css</span><br><span class="hljs-comment">http://localhost:3000/js/login.js</span><br><span class="hljs-comment"></span><br><span class="hljs-comment">通过带有 /bruce 前缀的地址访问 bruce 目录下的文件</span><br><span class="hljs-comment">http://localhost:8080/bruce/images/logo.png</span><br><span class="hljs-comment">*/</span><br></code></pre></td></tr></table></figure>

<h3 id="Express-路由"><a href="#Express-路由" class="headerlink" title="Express 路由"></a>Express 路由</h3><p>创建路由模块：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// router.js</span><br><br><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-comment">// 创建路由对象</span><br><span class="hljs-keyword">const</span> router = express.<span class="hljs-title class_">Router</span>()<br><br><span class="hljs-comment">// 挂载具体路由</span><br>router.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/list&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;Get user list.&#x27;</span>)<br>&#125;)<br>router.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/user/add&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;Add new user.&#x27;</span>)<br>&#125;)<br><br><span class="hljs-comment">// 向外导出路由对象</span><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = router<br></code></pre></td></tr></table></figure>

<p>注册路由模块：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-keyword">const</span> router = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./router&#x27;</span>)<br><br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><br><span class="hljs-comment">// 注册路由模块，添加访问前缀</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-string">&#x27;/api&#x27;</span>, router)<br><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h3 id="Express-中间件"><a href="#Express-中间件" class="headerlink" title="Express 中间件"></a>Express 中间件</h3><ul>
<li>中间件是指流程的中间处理环节</li>
<li>服务器收到请求后，可先调用中间件进行预处理</li>
<li>中间件是一个函数，包含 <code>req, res, next</code> 三个参数，<code>next()</code> 参数把流转关系交给下一个中间件或路由</li>
</ul>
<p>中间件注意事项；</p>
<ul>
<li>在注册路由之前注册中间件（错误级别中间件除外）</li>
<li>中间件可连续调用多个</li>
<li>别忘记调用 <code>next()</code> 函数</li>
<li><code>next()</code> 函数后别写代码</li>
<li>多个中间件共享 <code>req</code>、 <code>res</code>对象</li>
</ul>
<h4 id="全局中间件"><a href="#全局中间件" class="headerlink" title="全局中间件"></a>全局中间件</h4><p>通过 app.use() 定义的中间件为全局中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><br><span class="hljs-comment">// 定义第一个全局中间件</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;调用了第1个全局中间件&#x27;</span>)<br>  <span class="hljs-title function_">next</span>()<br>&#125;)<br><span class="hljs-comment">// 定义第二个全局中间件</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;调用了第2个全局中间件&#x27;</span>)<br>  <span class="hljs-title function_">next</span>()<br>&#125;)<br><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;User page.&#x27;</span>)<br>&#125;)<br><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="局部中间件"><a href="#局部中间件" class="headerlink" title="局部中间件"></a>局部中间件</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><br><span class="hljs-comment">// 定义中间件函数</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">mw1</span> = (<span class="hljs-params">req, res, next</span>) =&gt; &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;调用了第一个局部生效的中间件&#x27;</span>)<br>  <span class="hljs-title function_">next</span>()<br>&#125;<br><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">mw2</span> = (<span class="hljs-params">req, res, next</span>) =&gt; &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;调用了第二个局部生效的中间件&#x27;</span>)<br>  <span class="hljs-title function_">next</span>()<br>&#125;<br><br><span class="hljs-comment">// 两种定义局部中间件的方式</span><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/hello&#x27;</span>, mw2, mw1, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;hello page.&#x27;</span>))<br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/about&#x27;</span>, [mw1, mw2], <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;about page.&#x27;</span>))<br><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;User page.&#x27;</span>))<br><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;Express server running at http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="中间件分类"><a href="#中间件分类" class="headerlink" title="中间件分类"></a>中间件分类</h4><h5 id="1-应用级别的中间件"><a href="#1-应用级别的中间件" class="headerlink" title="1.应用级别的中间件"></a>1.应用级别的中间件</h5><ul>
<li>通过 <code>app.use()</code> 或 <code>app.get()</code> 或 <code>app.post()</code> ，绑定到 <code>app</code> 实例上的中间件</li>
</ul>
<h5 id="2-路由级别的中间件"><a href="#2-路由级别的中间件" class="headerlink" title="2.路由级别的中间件"></a>2.路由级别的中间件</h5><ul>
<li><p>绑定到 <code>express.Router()</code> 实例上的中间件，叫做路由级别的中间件。用法和应用级别中间件没有区别。应用级别中间件是绑定到 <code>app</code> 实例上，路由级别中间件绑定到 <code>router</code> 实例上。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><span class="hljs-keyword">const</span> router = express.<span class="hljs-title class_">Router</span>()<br><br>router.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">1</span>)<br>  <span class="hljs-title function_">next</span>()<br>&#125;)<br><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-string">&#x27;/&#x27;</span>, router)<br></code></pre></td></tr></table></figure></li>
</ul>
<h5 id="3-错误级别的中间件"><a href="#3-错误级别的中间件" class="headerlink" title="3.错误级别的中间件"></a>3.错误级别的中间件</h5><ul>
<li>用来捕获整个项目中发生的异常错误，从而防止项目异常崩溃的问题</li>
<li>错误级别中间件的处理函数中，必须有 4 个形参，形参顺序从前到后分别是 <code>(err, req, res, next)</code> 。</li>
<li>错误级别的中间件必须注册在所有路由之后</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>)<br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>()<br><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">&#x27;服务器内部发生了错误！&#x27;</span>)<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;Home page.&#x27;</span>)<br>&#125;)<br><br><span class="hljs-comment">// 定义错误级别的中间件，捕获整个项目的异常错误，从而防止程序的崩溃</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">err, req, res, next</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;发生了错误！&#x27;</span> + err.<span class="hljs-property">message</span>)<br>  res.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;Error：&#x27;</span> + err.<span class="hljs-property">message</span>)<br>&#125;)<br><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">80</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;Express server running at http://127.0.0.1&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h5 id="4-Express-内置中间件"><a href="#4-Express-内置中间件" class="headerlink" title="4.Express 内置中间件"></a>4.Express 内置中间件</h5><p>自 Express 4.16.0 版本开始，Express 内置了 3 个常用的中间件，极大的提高了 Express 项目的开发效率和体验：</p>
<ul>
<li><code>express.static</code> 快速托管静态资源的内置中间件，例如： HTML 文件、图片、CSS 样式等（无兼容性）</li>
<li><code>express.json</code> 解析 JSON 格式的请求体数据（有兼容性，仅在 4.16.0+ 版本中可用）</li>
<li><code>express.urlencoded</code> 解析 URL-encoded 格式的请求体数据（有兼容性，仅在 4.16.0+ 版本中可用）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">use</span>(express.<span class="hljs-title function_">json</span>())<br>app.<span class="hljs-title function_">use</span>(express.<span class="hljs-title function_">urlencoded</span>(&#123; <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> &#125;))<br></code></pre></td></tr></table></figure>

<h5 id="5-第三方中间件"><a href="#5-第三方中间件" class="headerlink" title="5.第三方中间件"></a>5.第三方中间件</h5><h3 id="CORS-跨域资源共享"><a href="#CORS-跨域资源共享" class="headerlink" title="CORS 跨域资源共享"></a>CORS 跨域资源共享</h3><h4 id="cors-中间件解决跨域"><a href="#cors-中间件解决跨域" class="headerlink" title="cors 中间件解决跨域"></a>cors 中间件解决跨域</h4><ul>
<li>安装中间件：<code>npm install cors</code></li>
<li>导入中间件：<code>const cors = require(&#39;cors&#39;)</code></li>
<li>配置中间件：<code>app.use(cors())</code></li>
</ul>
<h4 id="CORS"><a href="#CORS" class="headerlink" title="CORS"></a>CORS</h4><ul>
<li>CORS（Cross-Origin Resource Sharing，跨域资源共享）解决跨域，是通过 HTTP 响应头决定浏览器是否阻止前端 JS 代码跨域获取资源</li>
<li>浏览器的同源安全策略默认会阻止网页“跨域”获取资源。但如果接口服务器配置了 CORS 相关的 HTTP 响应头，就可解除浏览器端的跨域访问限制</li>
<li>CORS 主要在服务器端进行配置。客户端浏览器无须做任何额外的配置，即可请求开启了 CORS 的接口。</li>
<li>CORS 在浏览器中有兼容性。只有支持 XMLHttpRequest Level2 的浏览器，才能正常访问开启了 CORS 的服务端接口（例如：IE10+、Chrome4+、FireFox3.5+）。</li>
</ul>
<h4 id="CORS-常见响应头"><a href="#CORS-常见响应头" class="headerlink" title="CORS 常见响应头"></a>CORS 常见响应头</h4><ul>
<li><code>Access-Control-Allow-Origin</code>：制定了允许访问资源的外域 URL</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js">res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;http://bruceblog.io&#x27;</span>)<br>res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li><code>Access-Control-Allow-Headers</code></li>
<li>默认情况下，CORS 仅支持客户端向服务器发送如下的 9 个请求头：<code>Accept、Accept-Language、Content-Language、DPR、Downlink、Save-Data、Viewport-Width、Width 、Content-Type （值仅限于 text/plain、multipart/form-data、application/x-www-form-urlencoded 三者之一）</code></li>
<li>如果客户端向服务器发送了额外的请求头信息，则需要在服务器端，通过 A<code>ccess-Control-Allow-Headers</code> 对额外的请求头进行声明，否则这次请求会失败！</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;Content-Type, X-Custom-Header&#x27;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li><code>Access-Control-Allow-Methods</code></li>
<li>默认情况下，CORS 仅支持客户端发起 GET、POST、HEAD 请求。如果客户端希望通过 PUT、DELETE 等方式请求服务器的资源，则需要在服务器端，通过 <code>Access-Control-Alow-Methods</code> 来指明实际请求所允许使用的 HTTP 方法</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js">res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Methods&#x27;</span>, <span class="hljs-string">&#x27;POST, GET, DELETE, HEAD&#x27;</span>)<br>res.<span class="hljs-title function_">setHEader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Methods&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>)<br></code></pre></td></tr></table></figure>

<h4 id="CORS-请求分类"><a href="#CORS-请求分类" class="headerlink" title="CORS 请求分类"></a>CORS 请求分类</h4><h5 id="简单请求"><a href="#简单请求" class="headerlink" title="简单请求"></a>简单请求</h5><ul>
<li>请求方式：GET、POST、HEAD 三者之一</li>
<li>HTTP 头部信息不超过以下几种字段：无自定义头部字段、Accept、Accept-Language、Content-Language、DPR、Downlink、Save-Data、Viewport-Width、Width 、Content-Type（只有三个值 application/x-www-formurlencoded、multipart/form-data、text/plain）</li>
</ul>
<h5 id="预检请求"><a href="#预检请求" class="headerlink" title="预检请求"></a>预检请求</h5><ul>
<li>请求方式为 GET、POST、HEAD 之外的请求 Method 类型</li>
<li>请求头中包含自定义头部字段</li>
<li>向服务器发送了 application/json 格式的数据</li>
</ul>
<p>在浏览器与服务器正式通信之前，浏览器会先发送 OPTION 请求进行预检，以获知服务器是否允许该实际请求，所以这一次的 OPTION 请求称为“预检请求”。服务器成功响应预检请求后，才会发送真正的请求，并且携带真实数据</p>
<h2 id="数据库和身份认证"><a href="#数据库和身份认证" class="headerlink" title="数据库和身份认证"></a>数据库和身份认证</h2><h3 id="Node-操作-mysql"><a href="#Node-操作-mysql" class="headerlink" title="Node 操作 mysql"></a>Node 操作 mysql</h3><h4 id="配置-mysql-模块"><a href="#配置-mysql-模块" class="headerlink" title="配置 mysql 模块"></a>配置 mysql 模块</h4><ul>
<li>安装 mysql 模块</li>
</ul>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">npm <span class="hljs-keyword">install</span> mysql<br></code></pre></td></tr></table></figure>

<ul>
<li>建立连接</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> mysql = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;mysql&#x27;</span>)<br><br><span class="hljs-keyword">const</span> db = mysql.<span class="hljs-title function_">createPool</span>(&#123;<br>  <span class="hljs-attr">host</span>: <span class="hljs-string">&#x27;127.0.0.1&#x27;</span>,<br>  <span class="hljs-attr">user</span>: <span class="hljs-string">&#x27;root&#x27;</span>,<br>  <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;root&#x27;</span>,<br>  <span class="hljs-attr">database</span>: <span class="hljs-string">&#x27;test&#x27;</span>,<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>测试是否正常工作</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js">db.<span class="hljs-title function_">query</span>(<span class="hljs-string">&#x27;select 1&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err.<span class="hljs-property">message</span>)<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="操作-mysql-数据库"><a href="#操作-mysql-数据库" class="headerlink" title="操作 mysql 数据库"></a>操作 mysql 数据库</h4><ul>
<li>查询数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js">db.<span class="hljs-title function_">query</span>(<span class="hljs-string">&#x27;select * from users&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>插入数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// ? 表示占位符</span><br><span class="hljs-keyword">const</span> sql = <span class="hljs-string">&#x27;insert into users values(?, ?)&#x27;</span><br><span class="hljs-comment">// 使用数组的形式为占位符指定具体的值</span><br>db.<span class="hljs-title function_">query</span>(sql, [username, password], <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err.<span class="hljs-property">message</span>)<br>  <span class="hljs-keyword">if</span> (results.<span class="hljs-property">affectedRows</span> === <span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;插入成功&#x27;</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>向表中新增数据时，如果数据对象的每个属性和数据表的字段一一对应，则可以通过如下方式快速插入数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> user = &#123;<span class="hljs-attr">username</span>:<span class="hljs-string">&#x27;Bruce&#x27;</span>, <span class="hljs-attr">password</span>:<span class="hljs-string">&#x27;55520&#x27;</span>&#125;<br><span class="hljs-keyword">const</span> sql = <span class="hljs-string">&#x27;insert into users set ?&#x27;</span><br>db.<span class="hljs-title function_">query</span>(sql, user, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>更新数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> sql = <span class="hljs-string">&#x27;update users set username=?, password=? where id=?&#x27;</span><br>db.<span class="hljs-title function_">query</span>(sql, [username, password, id], <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>快捷方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> user = &#123;<span class="hljs-attr">id</span>:<span class="hljs-number">7</span>,<span class="hljs-attr">username</span>:<span class="hljs-string">&#x27;Bruce&#x27;</span>,<span class="hljs-attr">password</span>:<span class="hljs-string">&#x27;55520&#x27;</span>&#125;<br><span class="hljs-keyword">const</span> sql = <span class="hljs-string">&#x27;update users set ? where id=?&#x27;</span><br>db.<span class="hljs-title function_">query</span>(sql, [user, user.<span class="hljs-property">id</span>], <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>删除数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> sql = <span class="hljs-string">&#x27;delete from users where id=?&#x27;</span><br>db.<span class="hljs-title function_">query</span>(sql, id, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>使用 delete 语句会真正删除数据，保险起见，使用标记删除的形式，模拟删除的动作。即在表中设置状态字段，标记当前的数据是否被删除。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js">db.<span class="hljs-title function_">query</span>(<span class="hljs-string">&#x27;update users set status=1 where id=?&#x27;</span>, <span class="hljs-number">7</span>, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> &#123;<br>  ...<br>&#125;)<br></code></pre></td></tr></table></figure>

<h3 id="Web-开发模式"><a href="#Web-开发模式" class="headerlink" title="Web 开发模式"></a>Web 开发模式</h3><h4 id="服务端渲染"><a href="#服务端渲染" class="headerlink" title="服务端渲染"></a>服务端渲染</h4><p>服务器发送给客户端的 HTML 页面，是在服务器通过字符串的拼接动态生成的。因此客户端不需要使用 Ajax 额外请求页面的数据。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/index.html&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">const</span> user = &#123; <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;Bruce&#x27;</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">29</span> &#125;<br>  <span class="hljs-keyword">const</span> html = <span class="hljs-string">`&lt;h1&gt;username:<span class="hljs-subst">$&#123;user.name&#125;</span>, age:<span class="hljs-subst">$&#123;user.age&#125;</span>&lt;/h1&gt;`</span><br>  res.<span class="hljs-title function_">send</span>(html)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>优点：</p>
<ul>
<li>前端耗时短。浏览器只需直接渲染页面，无需额外请求数据。</li>
<li>有利于 SEO。服务器响应的是完整的 HTML 页面内容，有利于爬虫爬取信息。</li>
</ul>
<p>缺点：</p>
<ul>
<li>占用服务器资源。服务器需要完成页面内容的拼接，若请求比较多，会对服务器造成一定访问压力。</li>
<li>不利于前后端分离，开发效率低。</li>
</ul>
<h4 id="前后端分离"><a href="#前后端分离" class="headerlink" title="前后端分离"></a>前后端分离</h4><p>前后端分离的开发模式，依赖于 Ajax 技术的广泛应用。后端只负责提供 API 接口，前端使用 Ajax 调用接口。</p>
<p>优点：</p>
<ul>
<li>开发体验好。前端专业页面开发，后端专注接口开发。</li>
<li>用户体验好。页面局部刷新，无需重新请求页面。</li>
<li>减轻服务器的渲染压力。页面最终在浏览器里生成。</li>
</ul>
<p>缺点：</p>
<ul>
<li>不利于 SEO。完整的 HTML 页面在浏览器拼接完成，因此爬虫无法爬取页面的有效信息。Vue、React 等框架的 SSR（server side render）技术能解决 SEO 问题。</li>
</ul>
<h4 id="如何选择"><a href="#如何选择" class="headerlink" title="如何选择"></a>如何选择</h4><ul>
<li>企业级网站，主要功能是展示，没有复杂交互，且需要良好的 SEO，可考虑服务端渲染</li>
<li>后台管理项目，交互性强，无需考虑 SEO，可使用前后端分离</li>
<li>为同时兼顾首页渲染速度和前后端分离开发效率，可采用首屏服务器端渲染+其他页面前后端分离的开发模式</li>
</ul>
<h3 id="身份认证"><a href="#身份认证" class="headerlink" title="身份认证"></a>身份认证</h3><h4 id="Session-认证机制"><a href="#Session-认证机制" class="headerlink" title="Session 认证机制"></a>Session 认证机制</h4><p>服务端渲染推荐使用 Session 认证机制</p>
<h5 id="Express-中使用-Session-认证"><a href="#Express-中使用-Session-认证" class="headerlink" title="Express 中使用 Session 认证"></a>Express 中使用 Session 认证</h5><ul>
<li>安装 express-session 中间件</li>
</ul>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">npm <span class="hljs-keyword">install</span> express-session<br></code></pre></td></tr></table></figure>

<ul>
<li>配置中间件</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express-session&#x27;</span>)<br>app.<span class="hljs-title function_">use</span>(<br>  <span class="hljs-title function_">session</span>(&#123;<br>    <span class="hljs-attr">secret</span>: <span class="hljs-string">&#x27;Bruce&#x27;</span>, <span class="hljs-comment">// secret 的值为任意字符串</span><br>    <span class="hljs-attr">resave</span>: <span class="hljs-literal">false</span>,<br>    <span class="hljs-attr">saveUninitalized</span>: <span class="hljs-literal">true</span>,<br>  &#125;)<br>)<br></code></pre></td></tr></table></figure>

<ul>
<li>向 session 中存数据</li>
</ul>
<p>中间件配置成功后，可通过 <code>req.session</code> 访问 session 对象，存储用户信息</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/api/login&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  req.<span class="hljs-property">session</span>.<span class="hljs-property">user</span> = req.<span class="hljs-property">body</span><br>  req.<span class="hljs-property">session</span>.<span class="hljs-property">isLogin</span> = <span class="hljs-literal">true</span><br><br>  res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;login done&#x27;</span> &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>从 session 取数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/api/username&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">session</span>.<span class="hljs-property">isLogin</span>) &#123;<br>    <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;fail&#x27;</span> &#125;)<br>  &#125;<br>  res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;success&#x27;</span>, <span class="hljs-attr">username</span>: req.<span class="hljs-property">session</span>.<span class="hljs-property">user</span>.<span class="hljs-property">username</span> &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>清空 session</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/api/logout&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// 清空当前客户端的session信息</span><br>  req.<span class="hljs-property">session</span>.<span class="hljs-title function_">destroy</span>()<br>  res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;logout done&#x27;</span> &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="JWT-认证机制"><a href="#JWT-认证机制" class="headerlink" title="JWT 认证机制"></a>JWT 认证机制</h4><p>前后端分离推荐使用 JWT（JSON Web Token）认证机制，是目前最流行的跨域认证解决方案</p>
<h5 id="JWT-工作原理"><a href="#JWT-工作原理" class="headerlink" title="JWT 工作原理"></a>JWT 工作原理</h5><p>用户的信息通过 Token 字符串的形式，保存在客户端浏览器中。服务器通过还原 Token 字符串的形式来认证用户的身份。</p>
<p>Session 认证的局限性：</p>
<ul>
<li>Session 认证机制需要配合 Cookie 才能实现。由于 Cookie 默认不支持跨域访问，所以，当涉及到前端跨域请求后端接口的时候，需要做很多额外的配置，才能实现跨域 Session 认证。</li>
<li>当前端请求后端接口不存在跨域问题的时候，推荐使用 Session 身份认证机制。</li>
<li>当前端需要跨域请求后端接口的时候，不推荐使用 Session 身份认证机制，推荐使用 JWT 认证机制</li>
</ul>
<p>JWT 组成部分：</p>
<ul>
<li>Header、Payload、Signature</li>
<li>Payload 是真正的用户信息，加密后的字符串</li>
<li>Header 和 Signature 是安全性相关部分，保证 Token 安全性</li>
<li>三者使用 <code>.</code> 分隔</li>
</ul>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs stylus">Header<span class="hljs-selector-class">.Payload</span><span class="hljs-selector-class">.Signature</span><br><br>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9<span class="hljs-selector-class">.eyJpZCI6MTcsInVzZXJuYW1lIjoiQnJ1Y2UiLCJwYXNzd29yZCI6IiIsIm5pY2tuYW1lIjoiaGVsbG8iLCJlbWFpbCI6InNjdXRAcXEuY29tIiwidXNlcl9waWMiOiIiLCJpYXQiOjE2NDE4NjU3MzEsImV4cCI6MTY0MTkwMTczMX0</span>.bmqzAkNSZgD8IZxRGGyVlVwGl7EGMtWitvjGD-a5U5c<br></code></pre></td></tr></table></figure>

<p>JWT 使用方式：</p>
<ul>
<li>客户端会把 JWT 存储在 localStorage 或 sessionStorage 中</li>
<li>此后客户端与服务端通信需要携带 JWT 进行身份认证，将 JWT 存在 HTTP 请求头 Authorization 字段中</li>
<li>加上 Bearer 前缀</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml">Authorization: Bearer <span class="hljs-tag">&lt;<span class="hljs-name">token</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h5 id="Express-使用-JWT"><a href="#Express-使用-JWT" class="headerlink" title="Express 使用 JWT"></a>Express 使用 JWT</h5><ol>
<li><p>安装</p>
<ul>
<li>jsonwebtoken 用于生成 JWT 字符串</li>
<li>express-jwt 用于将 JWT 字符串解析还原成 JSON 对象</li>
</ul>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mipsasm">npm <span class="hljs-keyword">install </span><span class="hljs-keyword">jsonwebtoken </span>express-<span class="hljs-keyword">jwt</span><br></code></pre></td></tr></table></figure></li>
<li><p>定义 secret 密钥</p>
<ul>
<li>为保证 JWT 字符串的安全性，防止其在网络传输过程中被破解，需定义用于加密和解密的 secret 密钥</li>
<li>生成 JWT 字符串时，使用密钥加密信息，得到加密好的 JWT 字符串</li>
<li>把 JWT 字符串解析还原成 JSON 对象时，使用密钥解密</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;jsonwebtoken&#x27;</span>)<br><span class="hljs-keyword">const</span> expressJWT = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express-jwt&#x27;</span>)<br><br><span class="hljs-comment">// 密钥为任意字符串</span><br><span class="hljs-keyword">const</span> secretKey = <span class="hljs-string">&#x27;Bruce&#x27;</span><br></code></pre></td></tr></table></figure></li>
<li><p>生成 JWT 字符串</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/api/login&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  ...<br>  res.<span class="hljs-title function_">send</span>(&#123;<br>    <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>,<br>    <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;登录成功&#x27;</span>,<br>    <span class="hljs-comment">// jwt.sign() 生成 JWT 字符串</span><br>    <span class="hljs-comment">// 参数：用户信息对象、加密密钥、配置对象-token有效期</span><br>    <span class="hljs-comment">// 尽量不保存敏感信息，因此只有用户名，没有密码</span><br>    <span class="hljs-attr">token</span>: jwt.<span class="hljs-title function_">sign</span>(&#123;<span class="hljs-attr">username</span>: userInfo.<span class="hljs-property">username</span>&#125;, secretKey, &#123;<span class="hljs-attr">expiresIn</span>: <span class="hljs-string">&#x27;10h&#x27;</span>&#125;)<br>  &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>JWT 字符串还原为 JSON 对象</p>
<ul>
<li>客户端访问有权限的接口时，需通过请求头的 <code>Authorization</code> 字段，将 Token 字符串发送到服务器进行身份认证</li>
<li>服务器可以通过 express-jwt 中间件将客户端发送过来的 Token 解析还原成 JSON 对象</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// unless(&#123; path: [/^\/api\//] &#125;) 指定哪些接口无需访问权限</span><br>app.<span class="hljs-title function_">use</span>(<span class="hljs-title function_">expressJWT</span>(&#123; <span class="hljs-attr">secret</span>: secretKey &#125;).<span class="hljs-title function_">unless</span>(&#123; <span class="hljs-attr">path</span>: [<span class="hljs-regexp">/^\/api\//</span>] &#125;))<br></code></pre></td></tr></table></figure></li>
<li><p>获取用户信息</p>
<ul>
<li>当 express-jwt 中间件配置成功后，即可在那些有权限的接口中，使用 <code>req.user</code> 对象，来访问从 JWT 字符串中解析出来的用户信息</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/admin/getinfo&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(req.<span class="hljs-property">user</span>)<br>  res.<span class="hljs-title function_">send</span>(&#123;<br>    <span class="hljs-attr">status</span>: <span class="hljs-number">200</span>,<br>    <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;获取信息成功&#x27;</span>,<br>    <span class="hljs-attr">data</span>: req.<span class="hljs-property">user</span>,<br>  &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure></li>
<li><p>捕获解析 JWT 失败后产生的错误</p>
<ul>
<li>当使用 express-jwt 解析 Token 字符串时，如果客户端发送过来的 Token 字符串过期或不合法，会产生一个解析失败的错误，影响项目的正常运行</li>
<li>通过 Express 的错误中间件，捕获这个错误并进行相关的处理</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">err, req, res, next</span>) =&gt;</span> &#123;<br>  <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">&#x27;UnauthorizedError&#x27;</span>) &#123;<br>    <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">401</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;Invalid token&#x27;</span> &#125;)<br>  &#125;<br>  res.<span class="hljs-title function_">send</span>(&#123; <span class="hljs-attr">status</span>: <span class="hljs-number">500</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;Unknown error&#x27;</span> &#125;)<br>&#125;)<br></code></pre></td></tr></table></figure></li>
</ol>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%90%8E%E7%AB%AF/" class="category-chain-item">后端</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/node/">#node</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>node学习笔记</div>
      <div>http://dayu.com/2022/11/23/node学习笔记/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月23日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/11/27/react%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="react学习笔记">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">react学习笔记</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/11/21/VUE%E4%BD%BF%E7%94%A8element-ui%E8%87%AA%E5%B8%A6%E7%9A%84%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8/" title="VUE使用element-ui自带的富文本编辑器">
                        <span class="hidden-mobile">VUE使用element-ui自带的富文本编辑器</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments" lazyload>
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"你的appId","appKey":"你的appKey","path":"window.location.pathname","placeholder":"留言仅限讨论，禁止广告等行为","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"你的serverURLs","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/love.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxingxing.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxuehua.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/caidai.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
